import { useEffect } from "react";
import { Form, Button, Input, message } from "antd";
import { useForm } from "antd/es/form/Form";
import { getUserInfo, updateCaptcha, updateInfo } from "@api/updateinfo";
import "./index.less";

export interface UpdateInfo {
    headPic: string;
    nickName: string;
    email: string;
    captcha: string;
}

const layout1 = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}

export function UpdateInfo() {
    const [form] = useForm();

    useEffect(()=>{
        async function queryInfo() {
            const resp: any = await getUserInfo();
            console.log(resp);
            form.setFieldValue('headPic', resp.headPic);
            form.setFieldValue('nickName', resp.nickName);
            form.setFieldValue('email', resp.email);
        };
        queryInfo();
    }, []);

    const sendCaptcha = async () => {
        const address = form.getFieldValue('email');
        if(!address) return message.error('请输入邮箱地址');
        try {
            await updateCaptcha(address);
            message.success('发送成功');
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        } 
    }

    const onFinish = async (values: UpdateInfo) => {
        try {
            await updateInfo(values);
            message.success('用户信息更新成功');
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }

    return <div className="update-info">
        <Form
            form={form}
            {...layout1}
            colon={false}
            onFinish={onFinish}
        >
            <Form.Item label="头像" name='headPic' rules={[{required: true, message: '请输入头像'}]}>
                <Input />
            </Form.Item>
            <Form.Item label="昵称" name='nickName' rules={[{ required: true, message: '请输入昵称' }]}>
                <Input />
            </Form.Item>
            <Form.Item label="邮箱" name='email' rules={[{required: true, message: '请输入邮箱'},{ type: 'email', message: '请输入合法的邮箱' }]}>
                <Input />
            </Form.Item>
            <div className="update-info_captcha">
                <Form.Item label="验证码" name='captcha' rules={[{required: true, message: '请输入验证'}]}>
                    <Input />
                </Form.Item>
                <Button type="primary" onClick={sendCaptcha}>发送验证码</Button>
            </div>
            
            <Form.Item label=" ">
                <Button className="update-info_btn" type="primary" htmlType="submit">修改</Button>
            </Form.Item>
        </Form>
    </div>
}